package com.hutu.util;



import com.hutu.core.annotation.EnumClass;
import com.hutu.core.enums.BaseEnum;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 转换工具类
 * @param <T>
 */
public class ConvertUtil {

    /**
     * 转换单个对象里面的枚举值
     * @param t
     * @return
     * @param <T>
     */
    public static <T> void convertEnumItem(T t)  {
        List<T> list = new ArrayList<>();
        list.add(t);
        convertEnumItem(list);
    }

    /**
     * 转换列表里面的枚举值
     * @param list
     * @param <T>
     */
    public static <T> void convertEnumItem(List<T> list)  {
        if(list != null && list.size() > 0){
            for (T t : list){
                Class<?> aClass = t.getClass();
                Field[] declaredFields = aClass.getDeclaredFields();
                for (int i = 0; i < declaredFields.length; i++) {
                    Field field = declaredFields[i];
                    field.setAccessible(true);
                    Object value = null;
                    try {
                        value = field.get(t);
                    } catch (IllegalAccessException e) {
                        continue;
                    }

                    if(value == null)
                        continue;

                    EnumClass enumClassAnnotation = field.getAnnotation(EnumClass.class);
                    if(Objects.isNull(enumClassAnnotation))
                        continue;
                    Class enumClass = enumClassAnnotation.type();

                    try{
                        Method method = enumClass.getMethod("values");
                        BaseEnum inter[] = (BaseEnum[]) method.invoke(null, null);
                        for(BaseEnum e : inter){
                            if(String.valueOf(e.getCode()).equals(String.valueOf(value))){
                                Field fieldFill = aClass.getDeclaredField(field.getName() + "Str");
                                fieldFill.setAccessible(true);
                                fieldFill.set(t,e.getMessage());
                            }
                        }
                    }catch (Exception e){
                        continue;
                    }





                }
            }
        }
    }

}

